package master

import (
	"github.com/hwcer/cosgo/registry"
	"github.com/hwcer/cosgo/values"
	"github.com/hwcer/cosmo"
	"github.com/hwcer/yyds"
	"github.com/hwcer/yyds/context"
	"server/game/model"
)

func init() {
	Register(&character{})
}

type character struct {
}

func (this *character) Caller(node *registry.Node, handle *context.Context) interface{} {
	f := node.Method().(func(*character, *context.Context) interface{})
	return f(this, handle)
}

// Info 角色信息
func (this *character) Info(c *context.Context) interface{} {
	uid := c.GetString("uid")
	if uid == "" {
		return c.Error("uid is empty")
	}
	data := &model.Role{}
	if tx := db.Omit("goods").Find(data, uid); tx.Error != nil {
		return tx.Error
	} else if tx.RowsAffected == 0 {
		return c.Error("not exist")
	}
	return data
}

type CharacterGoods struct {
	Id    int32  `json:"id"`
	Name  string `json:"name"`
	Value int64  `json:"val"`
}

// Goods 道具信息
func (this *character) Goods(c *context.Context) interface{} {
	uid := c.GetString("uid")
	if uid == "" {
		return c.Error("uid is empty")
	}
	var rows []*model.Items
	if tx := db.Select("iid", "val").Find(&rows, uid); tx.Error != nil {
		return tx.Error
	} else if tx.RowsAffected == 0 {
		return nil
	}
	var goods []*CharacterGoods
	for _, v := range rows {
		goods = append(goods, &CharacterGoods{Id: v.IID, Name: yyds.Config.GetName(v.IID), Value: v.Value})
	}

	return goods
}

type RoleArgs struct {
	cosmo.Paging
	Uid string `json:"uid"`
}

type RoleItem struct {
	IID    int32         `bson:"iid" json:"id"`
	Value  int64         `bson:"val" json:"Val"`
	Name   string        `json:"name"`
	Update int64         `bson:"update" json:"Update"  ` //最后更新时间
	Attach values.Values `bson:"att" json:"att"`
}

func (this *character) Items(c *context.Context) interface{} {
	args := new(RoleArgs)
	if err := c.Bind(args); err != nil {
		return err
	}
	if args.Uid == "" {
		return c.Error("uid empty")
	}
	args.Paging.Init(100)
	var rows []*RoleItem
	args.Paging.Rows = &rows
	if tx := db.Model(&model.Role{}).Page(&args.Paging, "uid = ?", args.Uid); tx.Error != nil {
		return tx.Error
	}
	for _, item := range rows {
		item.Name = yyds.Config.GetName(item.IID)
	}

	return args
}
